<template>
  <div :class="['session_sider', { session_sider_screen: siderArray[3].active }]" v-show="!siderArray[2].active">
    <div :class="['h_s_bg']" v-show="!siderArray[3].active">
      <div class="homeHeaderFirstColse">
        <div class="homeSearch"></div>
        <input @click="copyShow = false" @contextmenu="copyRignt($event)" type="text" class="homeInput"
          placeholder="请输入关键字" maxlength="36" v-model="searchValue" ref="homeSearchInput" @focus="searchFocus"
          @click.stop.prevent="inputClick" @keyup.enter="entersearchKeyUp" tabindex="1" />
        <img draggable="false" src="static/image/home/clear_icon.png" class="s_clear_icon" @click="clearSearch"
          v-show="searchValue.trim() != ''" />
        <div id="search_tabs" class="tabs_parent m-no-select" v-show="searchResultShow" @click.stop.prevent="inputClick">
          <!-- zk127修改，动态切换value -->
          <div class="tabs_item" style="visibility: visible; flex-shrink: 0; overflow: auto">
            <div class="s_item_main">
              <ul class="search_main_list" @keyup.up="removeUp" @keyup.down="removeDown" @keyup.enter="choiceUserEnter"
                ref="mainScroll" tabindex="2">
                <li>
                  <div class="list_user_info">
                    <img draggable="false" src="static/image/search/message_logging.png"
                      class="s_person_icon img-border" />
                    <div class="list_main_info" @click="$emit('openSearchTab', '聊天记录', searchValue)">
                      <h3>搜聊天记录</h3>
                      <p class="info_main_detail" v-if="oldsearchval">
                        查找本地聊天记录"
                        <span style="color: #fa7500">{{ oldsearchval }}</span>"
                      </p>
                      <p class="info_main_detail" v-else>查找聊天记录</p>
                    </div>
                  </div>
                </li>
                <li>
                  <div class="list_user_info">
                    <img draggable="false" src="static/image/search/app_broadcast.png" class="s_person_icon img-border" />
                    <div class="list_main_info" @click="$emit('openSearchTab', '广播消息', searchValue)">
                      <h3>搜索广播</h3>
                      <p class="info_main_detail" v-if="oldsearchval">
                        查找广播"
                        <span style="color: #fa7500">{{ oldsearchval }}</span>"
                      </p>
                      <p class="info_main_detail" v-else>查找广播</p>
                    </div>
                  </div>
                </li>

                <li>
                  <div class="list_info_title">
                    <div class="list_title_text">
                      联系人
                      <span class="text_num" @click="$emit('setBookListShow', 2)">共{{
                        search_list_array.count ? search_list_array.count : 0
                      }}条
                        <img src="static\image\home\record_more.png"
                          style="position: relative; top: 1px; margin-left: 4px" />
                      </span>
                    </div>
                  </div>
                  <div v-for="(temp, index) in search_list_array.user" :class="[
                    'list_info_main',
                    { list_info_main_bg: temp.active },
                  ]" :key="index + 'key'">
                    <div class="list_user_info" @click.stop.prevent="searchToView($event, temp)"
                      @dblclick.stop.prevent="dbtoNewChat(temp)">
                      <!-- zk修改v-lazy换成：src -->
                      <img draggable="false" :src="!$isNull(temp.head)
                        ? `${$store.state.headPathUrl}${temp.id}${temp.head}.PNG`
                        : `static/image/home/person_${temp.gender == 2 ? 2 : 1
                        }.png`
                        " class="s_person_icon img-border" :onerror="defaultImg" />
                      <div class="list_main_info">
                        <!-- zk118修改<span v-html="$setKeyWords(temp.name,searchValue,"#fa7500")"></span> 参数依次是原字符串，关键字以及字体颜色 -->
                        <h3>
                          <div>
                            <span v-html="$replaceKeyWords(
                              temp.name,
                              oldsearchval,
                              '#fa7500',
                              16
                            )
                              "></span>{{
    temp.departmentname
    ? `(${temp.departmentname})`
    : ""
  }}
                          </div>
                        </h3>
                        <p class="info_main_detail">
                          <span style="display: inline-block; width: 54px">工/账号：</span>{{ temp.employeeno || "--" }}/{{
                            temp.account || "--"
                          }}
                        </p>
                        <p class="info_main_detail">
                          <span style="
                              display: inline-block;
                              width: 54px;
                              text-align: right;
                            ">手机：</span>{{ temp.mobile || "--" }}
                        </p>
                      </div>
                    </div>
                    <div v-if="index == search_list_array.user.length - 1 &&
                      search_list_array.count > search_list_array.user.length
                      " class="msg_more_search" @click.stop="more_search(2, 'user')">
                      显示更多
                    </div>
                  </div>
                </li>
                <li v-if="groupListShow">
                  <div class="list_info_title">
                    <div class="list_title_text">
                      我的群聊
                      <span class="text_num" @click="$emit('setBookListShow', 1)">共{{ groupListArr.length }}条
                        <img src="static\image\home\record_more.png"
                          style="position: relative; top: 1px; margin-left: 4px" />
                      </span>
                    </div>
                  </div>
                  <div v-for="(temp, index) in groupListShow" :key="index + 'key'" class="list_info_main"
                    @dblclick.stop.prevent="toNewChat(temp, true)">
                    <div class="list_user_info">
                      <img draggable="false" src="static/image/home/contact/group.png" class="s_person_icon img-border"
                        :onerror="defaultImg" />
                      <div class="list_main_info">
                        <h3>
                          <div>
                            <span v-html="$replaceKeyWords(
                              temp.name,
                              oldsearchval,
                              '#fa7500',
                              16
                            )
                              "></span>({{ temp.memberToal }}人)
                          </div>
                        </h3>
                        <p class="info_main_detail" v-if="temp.username">
                          包含:<span v-html="$replaceKeyWords(
                            temp.username,
                            oldsearchval,
                            '#fa7500'
                          )
                            "></span>
                        </p>
                      </div>
                    </div>
                    <div v-if="index == groupListShow.length - 1 &&
                      groupListArr.length > groupListShow.length
                      " class="msg_more_search" @click.stop="more_search(1)">
                      显示更多
                    </div>
                  </div>
                </li>
                <li style="padding-bottom: 10px">
                  <div class="list_info_title">
                    <div class="list_title_text">
                      应用
                      <span class="text_num" @click="$emit('workListShow')">共{{ appListArr.length }}条
                        <img src="static\image\home\record_more.png"
                          style="position: relative; top: 1px; margin-left: 4px" />
                      </span>
                    </div>
                  </div>
                  <div v-for="(temp, index) in appListArr" :key="index + 'key'" class="list_user_info"
                    @click="$emit('workListShow', temp)">
                    <img draggable="false" :src="`static/image/word/${temp.ICON}.png`" class="s_person_icon"
                      :onerror="defaultImg" />
                    <div class="list_main_info">
                      <h3>
                        <div>
                          <span v-html="$replaceKeyWords(
                            temp.NAME,
                            oldsearchval,
                            '#fa7500',
                            16
                          )
                            "></span>
                        </div>
                      </h3>
                    </div>
                  </div>
                </li>
              </ul>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div ref="minorSession" v-show="siderArray[0].active" class="homeMinor m-no-select" @scroll="minorScroll">
      <ul class="home_session_list">
        <template v-for="(item, index) in sessionList">
          <li @click="toChat(item)" v-if="index < 99" @contextmenu="contextmenu($event, item)" :class="{
            sessionBgColor: item.checked == true,
            active: item.sort == 1,
          }" :key="`${item.id}_session`" class="session_item">
            <div class="session_person_wrap" :class="{
              state_leave: item.status == 3,
              state_busy: item.status == 4,
              state_input_corner: item.status == 5,
              state_meeting: item.status == 6,
            }">
              <!-- zk修改v-lazy换成：src -->
              <img draggable="false" class="img-border" :class="{
                gray:
                  item.status == '7' && item.isGroup != '1'
                  && !item.systemId && item.id !== 'fileAssistant',
              }" :src="item.systemId
  ? 'static/image/home/chat/system_msg.png'
  : item.isGroup == '1'
    ? 'static/image/home/chat/session_group.png'
    : item.id == 'fileAssistant'
      ? 'static/image/word/app_transfer.png'
      : !$isNull(item.head)
        ? `${$store.state.headPathUrl}${item.id}${item.head}.PNG`
        : `static/image/home/person_${(item.gender || item.SEX) == 2 ? 2 : 1
        }.png`
  " :onerror="defaultImg" />
            </div>
            <div class="session_right_wrap">
              <div class="session_head">
                <div class="session_name">
                  {{
                    item.systemId
                    ? "系统消息"
                    : item.name
                      ? item.name
                      : item.NAME
                        ? item.NAME
                        : item.LEABLE
                          ? item.LEABLE
                          : ""
                  }}
                </div>
                <!-- 消息免打扰 -->
                <img draggable="false" src="static/image/home/disturb_icon.png" class="disturb_icon"
                  v-if="free_icon_sign(item.id)" />
                <div class="session_time">
                  {{ item.time | setTime }}
                </div>
              </div>
              <div class="session_value_w">
                <div class="session_value" v-html="toExpression(return_session_value(item))"></div>
                <div v-show="item.noRead && item.noRead > 0" :class="item.noRead >= 100
                  ? 'number_tip_three'
                  : item.noRead >= 10
                    ? 'number_tip_two'
                    : 'number_tip_one'
                  ">
                  {{ item.noRead >= 99 ? "99+" : item.noRead }}
                </div>
              </div>
            </div>
          </li>
        </template>
      </ul>
      <ul class="homeSessionMinor" :style="{ top: offsetTop + 'px', left: offsetLeft + 'px' }" ref="sessionMinor"
        v-show="minorShow">
        <li v-for="(item, index) in minorFunc" @click.stop="minorClick(index)" :key="'minorFunc' + index">
          {{
            index == 0
            ? !get_top_boolean(currentCheckItem.id)
              ? "置顶会话"
              : "移除置顶"
            : index == 2
              ? !free_icon_sign(currentCheckItem.id)
                ? "消息免打扰"
                : "移除免打扰"
              : item
          }}
        </li>
      </ul>
    </div>
    <div class="book_list_wrap" v-show="siderArray[1].active">
      <ul class="homeContact m-no-select">
        <li v-for="(item, index) in bookList" @click="setStructureListShow(item, index)"
          :class="{ bookListBgColor: item.show }" :key="index + '_book'">
          <img draggable="false" :src="item.url" />
          <span>{{ item.title }}</span>
        </li>
      </ul>
    </div>
    <div class="book_list_wrap" v-show="siderArray[2].active">
      <ul class="homeContact m-no-select">
        <template v-for="(item, index) in workList">
          <li v-if="(index != 0 || (index == 0 && myInfo.radioOf == 1)) &&
            item.id != 9
            " @click="setWorkListShow(item, index)" :class="{ bookListBgColor: item.show }" :key="index + '_book'">
            <img draggable="false" :src="item.url" />
            <span>{{ item.title }}</span>
            <div v-show="item.noRead && item.noRead > 0" class="tip_abs" :class="item.noRead >= 100
              ? 'number_tip_three'
              : item.noRead >= 10
                ? 'number_tip_two'
                : 'number_tip_one'
              ">
              {{ item.noRead >= 99 ? "99+" : item.noRead }}
            </div>
            <div v-show="item.id == 6 && officialManageTotal > 0" class="tip_abs" :class="officialManageTotal >= 100
              ? 'number_tip_three'
              : officialManageTotal >= 10
                ? 'number_tip_two'
                : 'number_tip_one'
              ">
              {{ officialManageTotal >= 99 ? "99+" : officialManageTotal }}
            </div>
          </li>
          <!-- 公文管理权限 -->
          <li v-if="item.id == 9 && myInfo.authDocument == 1" @click="setWorkListShow(item, index)"
            :class="{ bookListBgColor: item.show }" :key="index + '_book'">
            <img draggable="false" :src="item.url" />
            <span>{{ item.title }}</span>
          </li>
          <!-- <li v-else @click='setWorkListShow(item,index)' :class='{bookListBgColor:item.show}' :key="index+'_book'">
                        <img draggable="false" :src="item.url">
                        <span>{{item.title}}</span>
                        <div v-show="item.noRead&&item.noRead>0" class="tip_abs" :class="item.noRead>=100?'number_tip_three':item.noRead>=10?'number_tip_two':'number_tip_one'">{{item.noRead>=999?'999+':item.noRead}}</div>
                    </li> -->
        </template>
      </ul>
    </div>
    <!-- 工作台
    <div class="session_sider_screen_c" v-show='siderArray[3].active'>
        <div class="book_list_wrap_screen_title">
            <img src="static/image/screen/nav_application.png" />
            <div>工作台</div>
        </div>
        <Workbench 
          :screenPersonList="screenPersonList" 
          :isUpdateUser="isUpdateUser" 
          :oldScreenPersonList="oldScreenPersonList" 
          :isAutoOpenScreen="isAutoOpenScreen" 
          @getPersonFn="getPersonFn"
          @initIsAutoOpenScreen="initIsAutoOpenScreen" 
        >
        </Workbench>
    </div> -->
    <div class="session_sider_screen_c" v-show="siderArray[3].active">
      <div>
        <Work-App v-on="$listeners" :workList="workList" :officialManageTotal="officialManageTotal" />
      </div>
    </div>

    <div class="copy_paste_btn" v-if="copyShow" :style="{ top: pasteMenuTop + 'px', left: pasteMenuLeft + 'px' }">
      <span @click.stop.prevent="copyValue($event)">复制</span>
      <span @mousedown.stop="copyMain($event)">粘贴</span>
      <span @mousedown.stop="copyShow = false">取消</span>
    </div>
  </div>
</template>

<script>
import { mapState } from "vuex";
import Workbench from "../workbench/index";
import WorkApp from "../WorkApp/index";
import {
  getUserListInfoPage,
  getSetaTop,
  findGroupUserByName,
  getGroupByUserId,
  findApp,
} from "@/api/sessionListSider.js";
export default {
  components: {
    Workbench,
    WorkApp,
  },
  props: {
    workList: {
      type: Array,
      default: [],
    }, //办公事务
    setaList: {
      type: Object,
      default: {},
    },
    sessionList: {
      type: Array,
      default: [],
    },
    siderArray: {
      type: Array,
      default: [],
    },
    bookList: {
      type: Array,
      default: [], //通讯录列表
    },
    free_list: {
      type: Array,
      default: [],
    },
    minorShow: {
      type: Boolean,
      default: false,
    },
    searchResultShow: {
      type: Boolean,
      default: false,
    },
    searchUserList: {
      type: Array,
      default: [],
    },
    toExpression: {
      //zk1211新增，解决左侧表情不显示
      type: Function,
      default: null,
    },
    officialManageTotal: {
      type: Number,
      default: 0,
    },
    hideSearch: {
      type: Function,
      default: null,
    },
    screenPersonList: {
      // 同屏邀请
      type: Array,
      default: () => {
        return [];
      },
    },
    isUpdateUser: {
      type: Boolean,
      default: false,
    },
    oldScreenPersonList: {
      // 上一次同屏邀请
      type: Array,
      default: () => {
        return [];
      },
    },
    isAutoOpenScreen: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      seleText: '',
      copyText: '',
      pasteMenuTop: 0,
      pasteMenuLeft: 0,
      copyShow: false,
      activeTab: "name1", //zk新增，当前激活哪个tab,针对查找更多点击无效
      clickIndex: null, //zk120新增，当前点击哪条搜索结果
      minorFunc: ["置顶会话", "移出会话"], //功能表功能
      offsetTop: 0, //功能表位置上
      offsetLeft: 0, //功能表位置左
      currentCheckItem: [], //会话列表当前操作项
      searchHave: true,
      tabs_cur_name: -1, //标记选择的是 全部
      // defaultImg:'this.src="' + require('../../../static/image/home/person_1.png') + '"',
      defaultImg: 'this.src="static/image/home/person_1.png"',
      pageNum: 1,
      pageSize: 10,
      pageNumBroad: 1,
      pageNumGroup: 1,
      pageNumRecord: 1,
      recordTotal: null,
      search_func_array: [
        {
          label: "全部",
          name: "name1",
        },
        {
          label: "联系人",
          name: "name2",
        },
        {
          label: "聊天记录",
          name: "name3",
        },
        {
          label: "广播",
          name: "name4",
        },
      ],
      Timeout: null,
      userIndex: 0,
      sTime: null,
      searchValuePerson: "",
      startTimeS: "",
      endTimeS: "",
      broadIsRead: "全部",
      msgPage: 1,
      groupListShow: [],
      groupListArr: [],
      appListShow: [],
      appListArr: [],
    };
  },
  computed: {
    ...mapState([
      "myInfo",
      "personInfoList",
      "searchResultActive",
      "updateUserStatus",
      "nowMsgUserState",
    ]),
    tableId() {
      return this.myInfo.id;
    },
    sqlTable() {
      return {
        userHotKey: `user_hot_key`,
        uninterruptedList: `uninterrupted_list_${this.tableId}`, //免打扰列表
        userInformation: `user_information_${this.tableId}`, //用户信息表
        sessionList: `session_list_${this.tableId}`, //会话列表
        broadcastList: `broadcast_list_${this.tableId}`, //广播列表
        publicList: `public_list_${this.tableId}`, //公众号列表
        groupList: `group_list_${this.tableId}`, //群列表
        messageList: `message_list_${this.tableId}`, //群聊消息表
        privateList: `private_list_${this.tableId}`, //单聊消息表
        publicRecords: `public_records_${this.tableId}`, //公众号记录表
        groupUsers: `group_users_${this.tableId}`, //	groupMessageEnity: 'GroupMessageEnity_' + this.myInfo.id,
        systemTable: `system_${this.tableId}`,
        group_message: `group_message_${this.tableId}`, //群消息
        audit_notice: `audit_notice_${this.tableId}`, //审核通知
      };
    },
    msgPageTotal() {
      return Math.ceil(this.search_list_array.msg.length / 20);
    },
    broadPageTotal() {
      return Math.ceil(this.search_list_array.broad.length / 20);
    },
    search_list_array: {
      get() {
        return this.$store.state.search_list_array;
      },
      set(val) {
        this.$store.commit("setsearchListArr", val);
      },
    },
    searchValue: {
      get() {
        return this.$store.state.searchValue;
      },
      set(val) {
        this.$store.commit("setsearchValue", val);
      },
    },
    oldsearchval: {
      get() {
        return this.$store.state.oldsearchval;
      },
      set(val) {
        this.$store.commit("setoldsearchval", val);
      },
    },
  },
  watch: {
    searchResultShow: {
      handler(newValue, oldValue) {
        if (newValue) {
          if (this.searchValue == "") {
            this.searchKeyUp();
          }
          this.$refs.homeSearchInput.focus();
        }
      },
      deep: true,
      immediate: true,
    },
    searchResultActive() {
      if (!this.searchResultActive) {
        // this.searchResultShow=false;
        this.hideSearch(false); //zk120修改
      }
    },
    sessionList: {
      handler(newValue, oldValue) {
        this.$forceUpdate();
      },
      deep: true,
    },
    nowMsgUserState() {
      //更改当前发送消息用户状态
      for (let i = 0; i < this.sessionList.length; i++) {
        if (
          this.nowMsgUserState.id &&
          this.sessionList[i].id == this.nowMsgUserState.id
        ) {
          this.sessionList[i].status = this.nowMsgUserState.status;
          this.$forceUpdate();
        }
      }
    },
    //更改个人在线状态
    updateUserStatus() {
      //会话列表
      for (let i = 0; i < this.sessionList.length; i++) {
        if (this.sessionList[i].id == this.updateUserStatus.userId) {
          // console.log(
          //   this.updateUserStatus.status,
          //   this.updateUserStatus.userId,
          //   this.$getingTime(),
          //   "会话列表是否接收到用户在线状态更改=>"
          // );
          this.sessionList[i].status = this.updateUserStatus.status;
          this.$forceUpdate();
        }
      }
    },
    searchUserList() {
      this.search_list_array.user = this.searchUserList;
      this.$forceUpdate();
    },
    tabs_cur_name() {
      this.initAll(); // 初始化
    },
    sTime() {
      this.searchKeyUp();
    },
    broadIsRead() {
      this.searchKeyUp();
    },
    searchValue(val, oldval) {
      this.changeValueSearch(val, oldval);
    },
  },
  methods: {
    copyValue(e) {
      this.copyShow = false;

      // 到粘贴板
      // 2022/6/21空内容复制判断
      if (this.seleText == "") return this.$Message.warning("复制内容为空");
      // this.pasteVal = this.copyText;
      if (window.navigator.clipboard) {
        window.navigator.clipboard.writeText(this.seleText).then(
          () => {
            this.$Message.success("内容已复制到粘贴板");
          },
          () => {
            console.log("失败");
          }
        );
      } else {
        let value = this.seleText;
        let ipt = document.createElement("input");
        ipt.value = value;
        document.body.appendChild(ipt);
        ipt.select();
        document.execCommand("Copy");
        this.$Message.success("内容已复制到粘贴板");
        ipt.remove();
      }
    },
    copyMain(e) {
      // e.preventDefault();
      // console.log(this.copyText, 232);
      // document.execCommand("insertText", false, this.pasteVal);
      e.preventDefault();
      console.log(this.copyText, 232);
      let infs = this.$shell("GetClipboardData", []);
      infs = eval("(" + infs + ")");
      console.log(infs, 1289);
      let copyText = ''
      if (infs.return_code == 'TRUE') {
        copyText = infs.return_data.data
      }
      this.copyText = copyText
      document.execCommand("insertText", false, this.copyText);
      this.copyShow = false;
    },
    // 右键
    copyRignt(e) {


      e.preventDefault()
      this.getItemCoordinate(e)
      this.copyShow = true
      var selection = window.getSelection()
      var selectionText = selection.toString().trim()
      this.seleText = selectionText
      console.log(selectionText, 2550);

    },
    //获取坐标位置
    getItemCoordinate(e) {
      this.pasteMenuTop = e.clientY - 10 || 0;
      this.pasteMenuLeft = e.clientX - 10 || 0;
    },
    pageNext(type, n) {
      console.log(type, n);
      if (type == "msg") {
        this.msgPage += n;
      } else {
        this.pageNumBroad += n;
      }
    },
    showN(a) {
      let b = 1;
      a == "user" ? (b = 1) : a == "broad" ? (b = 3) : (b = 2);
      document.querySelectorAll(".ivu-tabs-tab")[b].click();
    },
    showDetail(temp, index) {
      if (this.clickIndex != index) {
        //不相等才打开
        this.clickIndex = index;
        this.$emit("toDetail", temp);
      }
    },
    toNewChat(i, b) {
      this.$emit("toNewChat", i, b);
    },
    dbtoNewChat(item) {
      //zk15标注，搜索结果双击
      if (item.id == this.myInfo.id) {
        this.$Message.warning("无法与自己聊天");
        return;
      }
      clearTimeout(this.Timeout);
      this.$emit("searchMdbTochat", item);
    },
    entersearchKeyUp() {
      //搜索框回车键焦点事件
      if (this.searchValue.replace(/\s+/g, "") == this.oldsearchval) {
        console.log(this.$refs.mainScroll, "this.$refs.mainScroll");
        //this.$refs.mainScroll.focus();
        this.initAll(); // 初始化
      } else {
        this.$refs.homeSearchInput.focus();
        this.searchKeyUp();
      }
    },
    searchKeyUp() {
      let info = this.searchValue.replace(/\s+/g, ""); // 去除空格
      let next = info == ""; // 是否为空
      // this.searchResultShow = !next;// 是否显示数据
      // this.hideSearch(!next);//zk120修改
      this.oldsearchval = info; //zk125新增，保存上次搜索内容，便于展示
      this.pageNum = 1; // 初始化分页 联系人
      this.pageSize = 10; // 初始化分页
      this.pageNumBroad = 1; // 初始化分页 广播
      this.pageNumRecord = 1; // 初始化分页 聊天记录
      this.searchHave = true; // 初始化显示加载更多
      let ct1 = "";
      let ct2 = new Date().getTime();
      if (!this.oldsearchval && !this.sTime && !this.searchValuePerson) {
        ct1 = ct2 - 86400000;
      }
      if (this.sTime) {
        ct1 = new Date(this.sTime[0]).getTime();
        ct2 = new Date(this.sTime[1]).getTime();
      }
      this.startTimeS = ct1 ? `AND time >= '${ct1}'` : "";
      this.endTimeS = ct2 ? `AND time <= '${ct2}'` : "";
      console.log(next, 674);
      if (!next) {
        this.$forceUpdate();
        this.searchFunction((res) => {
          this.search_list_array.user = res.data;
          this.search_list_array.count = res.count;
          console.log(this.search_list_array, 679);
          // this.search_list_array.user = NewList;
          // this.$forceUpdate();
          // 新增下载头像
          this.groupSearch();

          this.$emit("search_list_array_user", this.search_list_array.user);
          this.$emit("setSearchArray", info, true, 1); //zk119新增添加搜索词条
        });
      } else {
        this.search_list_array.user = [];
        this.search_list_array.count = 0;
        this.groupListShow = [];
        this.appListArr = [];
        this.groupListArr = [];
      }

      this.$parent.detailShow = false; //zk125新增
      this.clickIndex = null;
    },
    // 键盘up键
    removeUp(e) {
      this.userIndex--;
      if (this.userIndex <= 0) this.userIndex = 0;
      // 初始化背景色
      this.initBg();
      this.$set(this.search_list_array.user[this.userIndex], "active", true);
    },
    // 键盘down键
    removeDown(e) {
      this.userIndex++;
      // if (this.tabs_cur_name == -1) {
      //   if (this.userIndex >= 4) this.userIndex = 4;
      // } else if (this.tabs_cur_name == 0) {
      //   let len = this.search_list_array.user.length - 1;
      //   if (this.userIndex >= len) this.userIndex = len;
      // }
      let len = this.search_list_array.user.length - 1;
      if (this.userIndex >= len) this.userIndex = len;
      // 初始化背景色
      this.initBg();
      this.$set(this.search_list_array.user[this.userIndex], "active", true);
    },
    // 键盘enter键
    choiceUserEnter() {
      this.dbtoNewChat(this.search_list_array.user[this.userIndex]);
    },
    // 初始化背景色
    initBg() {
      if (this.search_list_array.user.length > 1) {
        let len = 0;
        // if (this.tabs_cur_name == -1)
        //   len =
        //     this.search_list_array.user.length > 5
        //       ? 5
        //       : this.search_list_array.user.length - 1;
        // else if (this.tabs_cur_name == 0)
        len = this.search_list_array.user.length - 1;
        for (let i = 0; i <= len; i++) {
          this.search_list_array.user[i]["active"] = false;
          this.$forceUpdate();
        }
      }
    },
    initAll() {
      if (
        this.search_list_array.user &&
        this.search_list_array.user.length > 0
      ) {
        // // 新增默认聚焦数据展示div
        // if (this.tabs_cur_name == -1) this.$refs["mainScroll0"][0].focus();
        // else if (this.tabs_cur_name == 0) this.$refs["mainScroll1"][0].focus();
        this.$refs.mainScroll.focus();
        // 初始化背景色
        this.initBg();
        // 初始化index
        this.userIndex = 0;
        // 默认选中第一个人
        this.$set(this.search_list_array.user[0], "active", true);
      }
    },
    clearSearch() {
      this.searchValue = "";
      //this.searchKeyUp()
    },
    minorScroll() {
      // this.minorShow=false;
      this.$emit("changeShow", "minorShow", false); //zk修改，让父组件来修改minorShow的值
    },
    setWorkListShow(item, index) {
      this.$emit("setWorkListShow", item, index);
    },
    setStructureListShow(item, index) {
      this.$emit("setStructureListShow", item, index);
    },
    //免打扰设置显示
    free_icon_sign(id) {
      for (let i in this.free_list) {
        if (this.free_list[i].userId == id) {
          return true;
        }
      }
      return false;
    },
    return_session_value(item) {
      let reg = /<(?!img).*?[^>]+>|&[^>]+;/g;
      return item.type == "screen"
        ? "[同屏]"
        : item.type == "article"
          ? "[分享文章]"
          : item.type == "image"
            ? "[图片]"
            : item.type == "file"
              ? "[文件]"
              : item.type == "GPS"
                ? "[位置]"
                : item.type == "audio"
                  ? "[语音]"
                  : item.type == "video"
                    ? "[视频]"
                    : item.type == "shareGroup"
                      ? "[群分享]"
                      : item.value && item.value.length > 0
                        ? (item.value.indexOf("@所有人") != -1 ||
                          item.value.indexOf(`@${this.myInfo.name}`) != -1) &&
                          item.sendId != this.myInfo.id
                          ? `<div style="color:red;">@你<div>`
                          : item.value
                            ? item.value
                              .replace(/<br>/g, "")
                              .replace(/style\s*?=\s*?(['"])[\s\S]*?\1/g, "")
                            : ""
                        : item.value
                          ? item.value
                            .replace(/<br>/g, "")
                            .replace(/style\s*?=\s*?(['"])[\s\S]*?\1/g, "")
                          : "";
    },
    contextmenu(e, item) {
      let rect = e.target.getBoundingClientRect();
      let client = document.documentElement.clientHeight;
      if (client && client - (rect.top + 130) <= 0) {
        this.offsetTop = client - 120;
      } else {
        this.offsetTop = rect.top;
      }
      this.offsetLeft = rect.left + 60;
      this.currentCheckItem = item;
      // this.minorShow = true;
      this.$emit("changeShow", "minorShow", true); //zk修改，让父组件来修改minorShow的值
    },
    toChat(item) {
      console.log(item, "当前聊天对象"); //zk调试用
      this.$emit("toChat", item);
    },
    searchToChat(temp) {
      console.log("点击广播了");
      this.$emit("openBroadItem", temp);
    },
    searchToView(e, item) {
      //zk15标注，搜索结果单击
      clearTimeout(this.Timeout);
      this.Timeout = setTimeout(() => {
        this.$emit("searchToView", e, item);
      }, 300);
    },
    more_search(num, temp) {
      if (num == 1) {
        this.groupListShow = [
          ...this.groupListShow,
          ...this.groupListArr.slice(
            this.pageNumGroup * 10,
            this.pageNumGroup * 10 + 10
          ),
        ];
        this.pageNumGroup++;
      } else if (num == 2) {
        console.log("加载更多");
        // 联系人
        this.pageNum++;
        this.searchFunction((res) => {
          if (res.data.length < 30) this.searchHave = false; // 如果查询的数据小于30 隐藏加载更多
          this.search_list_array.user = this.search_list_array.user.concat(
            res.data
          );
          // 新增下载头像
          this.$emit("search_list_array_user", this.search_list_array.user);
        });
      }
    },
    //计算搜索数据长度
    getLength(arr) {
      let a = 0;
      for (let i in arr) {
        a++;
      }
      return a;
    },
    //判断搜索选择项
    getCurRes(v) {
      let i = v == "user" ? 0 : v == "msg" ? 1 : 2;
      return i == this.tabs_cur_name;
    },
    inputClick() {
      this.$emit("inputClick");
    },
    searchFocus() {
      this.$emit("searchFocus");
    },
    // sql语句封装 1为搜索, 其他不需要参数
    operationalDatabase(statements, index) {
      let to = JSON.stringify({
        Sqlstr: statements,
      });
      return arguments[1]
        ? JSON.parse(this.$shellSQL(to, index))
        : JSON.parse(this.$shellSQL(to));
    },
    // 查询联系人
    searchFunction(success) {
      getUserListInfoPage({
        // 改为分页接口，新增两个字段
        name: this.oldsearchval,
        pageSize: this.pageSize,
        pageNumber: this.pageNum,
      })
        .then(success)
        .catch((res) => {
          console.log("搜索失败", res);
        });
    },
    //会话列表事件
    minorClick(index) {
      if (index == 0) {
        let path = `user/${!this.get_top_boolean(this.currentCheckItem.id) ? "add" : "del"
          }SetaTop.do`;
        let type = this.currentCheckItem.isGroup == 1 ? "2" : "1";
        getSetaTop(path, {
          userid: this.myInfo.id,
          type: type,
          objectId: this.currentCheckItem.id,
          sort: "0",
        })
          .then((res) => {
            this.$emit("getSetaTop");
            if (this.toInfo)
              this.topChat = !this.get_top_boolean(this.toInfo.id);
            // this.minorShow = false
            this.$emit("changeShow", "minorShow", false); //zk修改，让父组件来修改minorShow的值
            this.$forceUpdate();
          })
          .catch((error) => {
            console.log(error, "err=>");
          });
      } else if (index == 1) {
        // this.minorShow = false
        this.$emit("changeShow", "minorShow", false); //zk修改，让父组件来修改minorShow的值
        let isGroup = this.currentCheckItem.isGroup == 0 ? false : true;
        if (this.currentCheckItem.broadSendId) {
          let rep = this.operationalDatabase(
            `DELETE FROM ${this.sqlTable.broadcastList}`
          );
          this.broadShow = false;
        } else {
          let rep = this.operationalDatabase(
            `DELETE FROM ${this.sqlTable.sessionList} WHERE userId='${this.currentCheckItem.id}'`
          );
        }
        //移除系统消息
        if (this.currentCheckItem.systemId) {
          let rep = this.operationalDatabase(
            `DELETE FROM ${this.sqlTable.group_message}`
          );
          let _rep = this.operationalDatabase(
            `DELETE FROM ${this.sqlTable.audit_notice}`
          );
        }
        for (let i in this.sessionList) {
          if (this.sessionList[i].id == this.currentCheckItem.id) {
            this.sessionList.splice(i, 1);
            if (this.sessionList.length > 0) {
              this.toChat(this.sessionList[0]);
            } else if (this.sessionList.length == 0) {
              // this.chating=false;
              this.$store.commit("setChating", false); //zk修改，进来时没有聊天会话，chating是false
              this.$emit("chatingFun", false);
              this.$forceUpdate();
            }
            this.$forceUpdate();
            return;
          }
        }
      } else {
        let str = this.free_icon_sign(this.currentCheckItem.id);
        if (!str) {
          this.messageFree = true;
          this.$emit(
            "updateSessionMessageFree",
            this.messageFree,
            this.currentCheckItem.id
          );
        } else {
          this.messageFree = false;
          this.$emit(
            "updateSessionMessageFree",
            this.messageFree,
            this.currentCheckItem.id
          );
        }
        // this.minorShow = false;
        this.$emit("changeShow", "minorShow", false); //zk修改，让父组件来修改minorShow的值
      }
    },
    get_top_boolean(id) {
      return !!this.setaList[id];
    },
    getFreeList() {
      let info = this.operationalDatabase(
        `SELECT * FROM ${this.sqlTable.uninterruptedList};`,
        1
      );
      return info.list;
    },
    // 同屏邀请
    getPersonFn(obj) {
      this.$emit("getPersonFn", obj);
    },
    initIsAutoOpenScreen() {
      this.$emit("initIsAutoOpenScreen");
    },
    //我的群组搜索
    groupSearch() {
      findGroupUserByName({
        name: this.searchValue,
        userid: this.myInfo.id,
      }).then((res) => {
        let arr = res.data || [];
        this.groupListArr = this.groupFormat(arr);
        if (this.groupListArr.length > 10) {
          this.groupListShow = this.groupListArr.slice(0, 10);
        } else {
          this.groupListShow = this.groupListArr;
        }

        this.getAppList();
      });
    },
    groupFormat(data) {
      let arr = [];
      let obj = {};
      data.forEach((val) => {
        obj = {};
        obj.id = val.groupid;
        obj.name = val.groupname;
        obj.memberToal = val.count;
        obj.username = val.username;
        arr.push(obj);
      });
      return arr;
    },
    // 获取群列表
    getGroupList() {
      getGroupByUserId({
        userid: this.myInfo.id,
      }).then((res) => {
        this.groupListArr = res.data || [];
      });
    },
    //获取应用列表
    getAppList() {
      findApp({
        userid: this.myInfo.id,
        name: this.searchValue,
      }).then((res) => {
        if (res.code == 200) {
          this.appListArr = res.data ? res.data : [];
        } else {
          this.appListArr = [];
        }
      });
    },
    changeValueSearch(val, oldVal) {
      //监听input框的值改变
      clearTimeout(this.timer); //先清除之前的定时器
      this.timer = setTimeout(() => {
        if (oldVal !== val) {
          this.searchKeyUp();
        }
      }, 500);
    },
  },
  mounted() {
    this.searchKeyUp();
    this.getGroupList();
    // setTimeout(() => {
    //   console.log(this.sessionList, "默认显示第一聊天界面");
    //   this.toChat(this.sessionList[0]);
    // }, 1000);

    // const domClick = () => {
    //   console.log(7787878);
    //   this.copyShow = false;
    // };
    // document.addEventListener("click", domClick);
    // this.$once("hook:beforeDestroy", () => {
    //   document.removeEventListener("click", domClick);
    // });
  },
};
</script>
<style scoped>
.s_item_search>>>.el-input__inner {
  width: 220px !important;
  padding: 0 10px;
  height: 32px;
}

.s_item_search>>>.el-range-input {
  width: 50%;
  line-height: 32px;
}

.s_item_search>>>.el-range-separator {
  width: 7%;
  padding: 0;
}

.s_item_search>>>.el-icon-time {
  display: none;
}

.s_item_search>>>.el-range-input {
  font-size: 12px;
}

#search_tabs>>>.ivu-tabs-bar {
  margin-bottom: 0;
}

#search_tabs>>>.ivu-tabs-nav {
  height: 38px;
}

.file_pic {
  width: 14px;
  height: 14px;
}

.s_item_search .my_el_select>>>.el-input {
  width: 140px !important;
}

.s_item_search .my_el_select>>>.el-input__icon {
  line-height: 34px;
}

.el-select-dropdown {
  width: 140px !important;
}

.s_item_search .my_el_select>>>input {
  width: 140px !important;
}

.my_el_select {
  width: 73%;
}

.flagNoRead {
  width: 6px;
  height: 6px;
  border-radius: 3px;
  background: #ff2200;
  position: relative;
  left: -10px;
  top: -10px;
}

.copy_paste_btn {
  position: fixed;
  top: 0;
  left: 0;
  overflow: hidden;
  font-size: 1.2em;
  color: #fff;
  cursor: pointer;
  background: rgba(0, 0, 0, 0.7);
  border-radius: 4px;
  display: flex;
  flex-direction: column;
  z-index: 99999;

}

.copy_paste_btn>span {
  padding: 0.7em;

}

.copy_paste_btn>span:hover {
  background: #999;
}
</style>
